﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System.Text;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_DeviceTypeController : MvcControllerBase
    {
        //
        // GET: /ResourceManage/RS_DeviceType/
        private DeviceTypeBLL deviceTypeBLL = new DeviceTypeBLL();
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }


        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult DatasForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult PartsForm()
        {
            return View();
        }

        #endregion
        #region 查询数据
        /// <summary>
        /// 查询设备类别列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetListJson(string condition, string keyword, string DeviceTypeId)
        {
            var data = deviceTypeBLL.GetList().OrderBy(t => t.Sort).ToList();
            if (!string.IsNullOrEmpty(DeviceTypeId))
            {
                data = data.Where(t => t.Id == DeviceTypeId || t.ParentId == DeviceTypeId).ToList();
                //data = data.TreeWhere(t => t.Id == DeviceTypeId, "Id");
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                #region 多条件查询
                switch (condition)
                {
                    case "Name":        //项目名
                        data = data.TreeWhere(t => t.Name.Contains(keyword), "Id");
                        break;
                    case "Code":      //项目值
                        data = data.TreeWhere(t => t.Code.Contains(keyword), "Id");
                        break;
                    default:
                        break;
                }
                #endregion
            }

            var TreeList = new List<TreeGridEntity>();
            foreach (DeviceTypeEntity item in data)
            {
                TreeGridEntity tree = new TreeGridEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.parentId = data.Count(t => t.Id == item.ParentId) == 0 ? "0" : item.ParentId;
                tree.expanded = true;
                tree.hasChildren = hasChildren;
                tree.entityJson = item.ToJson();
                TreeList.Add(tree);
            }
            return Content(TreeList.TreeJson());
        }
        /// <summary>
        /// 查询设备参数列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetDatasListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = deviceTypeBLL.GetDatasList(pagination, queryJson).Join(deviceTypeBLL.GetList(), x => x.Type, y => y.Id, (x, y) => new
            {
                x.Id,
                x.Name,
                x.Required,
                x.SortCode,
                x.Type,
                x.Value,
                x.ValueType,
                x.Criterition,
                x.DataSourceId,
                x.DataSourceType,
                x.DefaultValue,
                TypeName = y.Name
            }).OrderBy(t => t.SortCode).ToList();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 查询设备零配件列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetPartsListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = deviceTypeBLL.GetPartsList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 查询设备零配件列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetPartsList(string queryJson)
        {
            return Content(deviceTypeBLL.GetPartsList(queryJson).ToJson());
        }


        /// <summary>
        /// 种类列表 
        /// </summary>
        /// <param name="keyword">关键字查询</param>
        /// <returns>返回树形Json</returns>
        [HttpGet]
        public ActionResult GetTreeJson()
        {
            var data = deviceTypeBLL.GetList().ToList();
            var treeList = new List<TreeEntity>();
            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId;
                tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                tree.Attribute = "Sort";
                tree.AttributeValue = item.Sort.ToString();
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        public ActionResult GetCheckBoxTreeJson()
        {
            var data = deviceTypeBLL.GetList().ToList();
            var treeList = new List<TreeEntity>();
            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId;
                tree.showcheck = true;
                tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 种类列表 
        /// </summary>
        /// <param name="keyword">关键字查询</param>
        /// <returns>返回树形Json</returns>
        [HttpGet]
        public ActionResult GetHtml()
        {
            var data = deviceTypeBLL.GetList().ToList();
            StringBuilder _Html = new StringBuilder();
            _Html.Append("<li><a href='#' onclick='clickType(this,\"\")'><i class=\"fa fa-folder\"></i>所有</a></li>");
            foreach (DeviceTypeEntity item in data)
            {
                _Html.Append("<li><a href='#' onclick='clickType(this,\"" + item.Id + "\")'><i class=\"fa fa-folder\"></i> " + item.Name + "</a></li>");
            }
            return Content(_Html.ToString());
        }

        /// <summary>
        /// 实体 
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns>返回对象Json</returns>
        [HttpGet]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = deviceTypeBLL.GetEntity(keyValue);
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult GetPartsFormJson(string keyValue)
        {
            var data = deviceTypeBLL.GetPartEntity(keyValue);
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult GetDatasFormJson(string keyValue)
        {
            var data = deviceTypeBLL.GetDataEntity(keyValue);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取参数值列表
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="DeviceTypeId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetDatasList(string keyValue, string DeviceTypeId)
        {
            var DeviceDatas = deviceTypeBLL.GetDatasList(DeviceTypeId).ToList();
            var DeviceDatasInstance = deviceTypeBLL.GetDatasInstanceList(keyValue).ToList();
            var data = from a in DeviceDatas
                       join b in DeviceDatasInstance on a.Id equals b.DeviceDatasId into temp
                       from tt in temp.DefaultIfEmpty()
                       select new { DeviceDatasId = a.Id, a.Name, a.Type, a.DataSourceType, a.DefaultValue, a.Required, a.DataSourceId, a.SortCode, a.Criterition, Value = tt != null ? tt.Value : a.DefaultValue, a.ValueType };
            var _Html = "";
            if (data != null && data.Count() > 0)
            {
                foreach (var item in data)
                {
                    _Html += "<tr><th class='formTitle'>" + item.Name + " </th> <td class='formValue'>";
                    switch (item.ValueType)
                    {
                        case "text": _Html += "<input id=" + item.DeviceDatasId + "  type='text' class='form-control' value='" + item.Value + "'  />"; break;
                        default: break;
                    }
                    _Html += "</td></tr>";
                }
            }
            return Content(new { html = _Html, count = data.Count() }.ToJson());
        }
        #endregion

        #region 验证数据
        /// <summary>
        /// 种类名称不能重复
        /// </summary>
        /// <param name="Name">种类名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistName(string Name, string keyValue)
        {
            bool IsOk = deviceTypeBLL.ExistName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        /// <summary>
        /// 种类编号不能重复
        /// </summary>
        /// <param name="Code">种类编号</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistCode(string Code, string keyValue)
        {
            bool IsOk = deviceTypeBLL.ExistCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion

        #region 保存数据
        /// <summary>
        /// 保存种类表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="deviceTypeEntity">种类实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, DeviceTypeEntity deviceTypeEntity)
        {
            deviceTypeBLL.SaveForm(keyValue, deviceTypeEntity);
            return Success("操作成功。");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemoveForm(string keyValue)
        {
            try
            {
                deviceTypeBLL.RemoveForm(keyValue);
                return Success("删除成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SavePartsForm(string keyValue, DevicePartsEntity devicePartsEntity)
        {
            deviceTypeBLL.SavePartsForm(keyValue, devicePartsEntity);
            return Success("操作成功。");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemovePartsForm(string keyValue)
        {
            deviceTypeBLL.RemovePartsForm(keyValue);
            return Success("删除成功。");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveDatasForm(string keyValue, DeviceDatasEntity deviceDatasEntity)
        {
            deviceTypeBLL.SaveDatasForm(keyValue, deviceDatasEntity);
            return Success("操作成功。");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemoveDatasForm(string keyValue)
        {
            deviceTypeBLL.RemoveDatasForm(keyValue);
            return Success("删除成功。");
        }
        #endregion
    }
}
